package com.umeox.watch.moto.launcher.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.event.HorizontalScrollToPagerEvent;
import com.umeox.watch.moto.pedometer.util.StepManager;
import com.umeox.watch.moto.pedometer.util.StepUtils;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class HealthNumberClockView extends RelativeLayout implements View.OnClickListener, StepManager.StepInfoChangeListener {
    public static final int WHAT = 500;
    private final Typeface mTfJosefinSansBold;
    private Typeface mTfJosefinSansLight;
    private Typeface mTfLatoBold;
    private TextView mStepCountTv;
    private TextView mDistanceTv;
    private TextView mDateTimeTv;
    private Context mContext;
    private TextView mCaloriesTv;
    public final SimpleDateFormat DATE_FORMAT_24 = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    public final SimpleDateFormat DATE_FORMAT_12 = new SimpleDateFormat("hh:mm:ss", Locale.getDefault());
    private TextView mStepGoalTv;
    private double mAccountHeight;
    private double mAccountWeight;
    private int mTarget = 5000;
    private int mSteps;
    private DecimalFormat mDistanceFormat = new DecimalFormat("#.##");
    private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);

    @SuppressLint("HandlerLeak")
    private final Handler mUpdateTimeHandler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            if (WHAT == message.what) {
                updateDateTime();
                long timeMs = System.currentTimeMillis();
                long delayMs = INTERACTIVE_UPDATE_RATE_MS
                        - (timeMs % INTERACTIVE_UPDATE_RATE_MS);
                mUpdateTimeHandler.sendEmptyMessageDelayed(WHAT, delayMs);
            }
        }
    };
    private MultiProgressBar mMultiProgressBar;
    private int mDistanceUnit;


    public HealthNumberClockView(Context context) {
        this(context, null);
    }

    public HealthNumberClockView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HealthNumberClockView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        AssetManager mgr = context.getAssets();
        mTfJosefinSansBold = Typeface.createFromAsset(mgr, "font/JosefinSans_Bold.ttf");
        mTfJosefinSansLight = Typeface.createFromAsset(mgr, "font/JosefinSans_Light.ttf");
        mTfLatoBold = Typeface.createFromAsset(mgr, "font/Lato_Bold.ttf");
        initView();
        //TODO
        mDistanceUnit = 1;//DataProvider.getDistanceUnit();
    }

    private void initView() {
        final View view = LayoutInflater.from(mContext).inflate(R.layout.view_health_number_clock, this);
        mStepCountTv = view.findViewById(R.id.tv_step_count);
        mDateTimeTv = view.findViewById(R.id.tv_date);
        mStepGoalTv = view.findViewById(R.id.tv_step_goal);
        mDistanceTv = view.findViewById(R.id.tv_distance);
        mCaloriesTv = view.findViewById(R.id.tv_calories);

        mMultiProgressBar = view.findViewById(R.id.progress_multi);
        view.findViewById(R.id.iv_pedometer).setOnClickListener(this);

        mMultiProgressBar.setFirstColors(0xFFFF1411, 0xFFFD08AB, 0xFF340914);
        mMultiProgressBar.setSecondColors(0xFF9BFF04, 0xFF9BFF04, 0xFF2C4204);
        mMultiProgressBar.setThirdColors(0xFF1AD5DE, 0xFF1AD5DE, 0xFF133D3C);
    }

    private void initData() {
        final int todayStepCount = mSteps;
        double stepDistance = StepUtils.getDistance(mAccountHeight);
        double distance = stepDistance * todayStepCount / 100;
        double calories = StepUtils.getKcal(mAccountWeight, distance / 1000);
        mCaloriesTv.setText(String.valueOf(calories));

        final double v = distance / (mDistanceUnit == 0 ? 1000 : 1609);

        mDistanceTv.setText(mDistanceFormat.format(todayStepCount <= 0 ? 0 : Math.max(v, 0.01)));
        mStepCountTv.setText(String.valueOf(todayStepCount));
        mStepGoalTv.setText(String.valueOf(mTarget));

        mMultiProgressBar.setFirstProgress(todayStepCount * 100.0f / mTarget);
        final double stepDistanceMax = stepDistance * 5000 / 100;
        final float distancePercent = (float) (distance * 100 / stepDistanceMax);
        mMultiProgressBar.setThirdProgress(distancePercent);
        mMultiProgressBar.setSecondProgress((float) (calories * 100 / StepUtils.getKcal(mAccountWeight, stepDistanceMax / 1000)));
    }

    private void updateTimer() {
        mUpdateTimeHandler.removeMessages(WHAT);
        mUpdateTimeHandler.sendEmptyMessage(WHAT);
    }


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        StepManager.getInstance().addStepInfoChangeListener(this);
        updateTimer();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        StepManager.getInstance().removeStepInfoChangeListener(this);
        mUpdateTimeHandler.removeMessages(WHAT);
    }


    /**
     * 更新日期\时间
     */
    private void updateDateTime() {
        final boolean hourFormat_24 = DateFormat.is24HourFormat(mContext);
        SimpleDateFormat dateFormat = hourFormat_24 ? DATE_FORMAT_24 : DATE_FORMAT_12;
        final long millis = System.currentTimeMillis();
        final String format = dateFormat.format(millis);
        mDateTimeTv.setText(format);
    }

    @Override
    public void onClick(View v) {
        EventBus.getDefault().post(new HorizontalScrollToPagerEvent(0));
    }

    @Override
    public void onStepInfoChange(int steps, int target, double height, double weight) {
        mTarget = target;
        mAccountHeight = height;
        mAccountWeight = weight;
        mSteps = steps;
        initData();
    }
}
